<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px" :label-position="labelPosition">
      <el-form-item label="客户" prop="khm">
        <el-select
            v-model="queryParams.khm"
            placeholder="请输入客户"
            clearable
            @change="changeSelectClient3"
            filterable
            :loading="selectClient3Loading"
        >
            <el-option
                v-for="(item, index) in client3List"
                :key="index"
                :label="item.khmc"
                :value="item.khmc"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="当前应收月份" prop="e3">
        <el-date-picker
          v-model="queryParams.e3"
          value-format="yyyy-MM"
          type="month"
          placeholder="选择月"
          @change="monthChange()">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所选日期">
        <el-date-picker
          v-model="settlementStatementDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="settlementStatementDateChange()">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="mt20 mb20 ml10 font-size-14" v-show="total && zfySum != ''">
      <span>共</span>
      <span class="text-danger">{{ total }}</span>
      <span>条记录，总费用</span>
      <span class="text-danger">{{ zfySum }}</span>
      <span>元</span>
    </div>
    <el-row :gutter="10" class="mb8" type="flex" align="middle">
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="handleExportSelection" :loading="exportLoading" :disabled="selection.length === 0 || exportLoading">导出</el-button>
        </el-col>
        <el-col :span="22.5">
          <div class="mt20 mb20 ml10">
            <i class="el-icon-warning-outline font-size-14"></i>
            <span class="ml5 font-size-12 color-606266">仓租按所选的日期范围天数计算，选择月份则自动按整月天数计算；支持查询未来产生的仓租</span>
          </div>
        </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="settlementStatementList"
      @selection-change="handleSelectionChange"
    >
    <af-table-column type="selection" width="50" align="center" /> 
    <af-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="left">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="openSettlementStatementDetail(scope.row)"
            v-hasPermi="['zhcloud:sjzl:list']"
          >费用明细</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleExport(scope.row)"
            v-hasPermi="['zhcloud:sjzl:export']"
          >导出Excel</el-button>
        </template>
      </af-table-column> 
      <af-table-column prop="allName" label="客户"></af-table-column>
      <af-table-column prop="zfy" label="应收费用"></af-table-column>
      <!-- <af-table-column prop="isprint" label="是否打印"></af-table-column> -->
      <!-- <af-table-column prop="zfy_new" label="应收费用"></af-table-column> -->
    </el-table>
     <!-- <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getList"
      /> -->
  </div>

</template>

<script>
import { getSettlementStatement } from "@/api/storage/dataOverview/settlementStatement"
import { selectClient3 } from "@/api/storage/customer"
import { getlastMonth } from '@/utils'
import { AMOUNT_DIGIT } from '@/utils/constant'
import { resolve } from "path"

export default {
  name: "SettlementStatement",
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //表格加载
      loading:true,
       //对齐
      labelPosition: "right",
      //客户加载
      selectClient3Loading:true,
      //导出加载
      exportLoading: false,
      //日期
      settlementStatementDate:"",
      // 查询参数
      queryParams: {
        e1: "",
        e2: "",
        e3:"",
        khm: "",
        spckmc:"" ,
        spgh:"" ,
        spkhmcid:"" ,
        sptm:"",
      },
      //获取客户参数
      selectClient3Query: {
        name1:""
      },
      //结算对账单列表
      settlementStatementList: [],
      //客户列表
      client3List: [],
      //选中数据
      selection:[],
      // //页数
      // pageSize: 10,
      // //页码
      // pageNum:1,
      // 总条数
      total: 0,
      //总费用
      zfySum:"",
    };
  },
  beforeRouteEnter(to, from, next) {
    const params = to.params
    next(vm => {   
      if(Object.keys(params).length > 0) {
        if(to.params.refresh == true) {
          vm.getList()
        }
      }
    })
  },
  created() {
    this.queryParams.e3 = getlastMonth()
    this.getClient3()
    this.getList()
  },
  methods: {
     /**获取客户 */
    getClient3() {
      this.selectClient3Loading = true
      selectClient3(this.selectClient3Query).then(response => {
        this.client3List = response.data
        this.selectClient3Loading = false
      });
    },

    /** 结算对账总览 */
    getList() {
      this.loading = true
      getSettlementStatement(this.queryParams).then(response => {
        const data = response.data
        let zfySum = 0
        for(let i in data) {
          zfySum += data[i].zfy
        }
        this.zfySum = zfySum.toFixed(AMOUNT_DIGIT)
        this.settlementStatementList = data
        this.total = data.length
        this.loading = false
      });
    },

    /**选择客户 */
    changeSelectClient3() {
        this.getList()
    },

     /**选择日期 */
    settlementStatementDateChange() {
      if(this.queryParams.e3) {
        this.settlementStatementDate = ""
        this.$modal.msgError("不能同时选择两个日期")
      } else {
        this.queryParams.e1 = this.settlementStatementDate?this.settlementStatementDate[0]:""
        this.queryParams.e2 = this.settlementStatementDate?this.settlementStatementDate[1]:""
        this.getList()
      }
    },
    /**选择月份 */
    monthChange() {
      if(this.queryParams.e1 || this.queryParams.e2) {
        this.queryParams.e3 = ""
        this.$modal.msgError("不能同时选择两个日期")
      } else {
        this.getList()
      }
    },

    /**费用明细 */
    openSettlementStatementDetail(data) {
      this.$router.push({path:"/storage/dataOverview/settlementStatement/settlementStatementDetail", query:{
        spkhmcid:data.spkhmcid,
        e1:this.queryParams.e1,
        e2:this.queryParams.e2,
        e3:this.queryParams.e3
      }})
    },

    /**导出excel */
    handleExport(row) {
      return new Promise((resolve, reject) => {
        let title = ""
        if(this.queryParams.e3) {
          title = `对账${this.queryParams.e3 + row.allName}`
        }
        if(this.queryParams.e1 && this.queryParams.e2) {
          title = `对账${this.queryParams.e1}-${this.queryParams.e2 + row.allName}`
        }
        let data = JSON.parse(JSON.stringify(this.queryParams))
        data = {
          ...data,
          spkhmcid:row.spkhmcid,
          downloadType:"json"
        }
        let a = setTimeout(() => {
          this.download('/storage/sjzl/export3', data, `${title}.xlsx`, true).then(() => {
            resolve()
          }).catch(err => {
            this.exportLoading = false
            reject()
          })
          clearTimeout(a)
        }, 1000)
      })
    },

    async handleExportSelection() {
      const selection = this.selection
      if (selection.length > 0) {
        this.exportLoading  = true
        for(let i in selection) {
          await this.handleExport(selection[i])
        }
        this.exportLoading = false
      } else {
        this.$modal.msgError('请勾选数据');
      }
    },

     // 多选框选中数据
     handleSelectionChange(selection) {
      this.selection = selection
    },

    /**enter键触发 */
    enterClick(e) {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.getClient3()
      this.getList()
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    },
  }
}
</script>
